//
//  YWSearchCom.m
//  YunWu
//
//  Created by 古俊杰 on 2017/5/31.
//  Copyright © 2017年 曲虹亮. All rights reserved.
//

#import "YWSearchCom.h"
#import "YWSearchResultController.h"
#import "UIView+Category.h"

#define RGB(r, g, b)      [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
#define RGBA(r, g, b, a)  [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]

#define Main_Screen_Width       [[UIScreen mainScreen] bounds].size.width
#define Main_Screen_Height      [[UIScreen mainScreen] bounds].size.height

@interface YWSearchCom () <UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate>
{
   
    
}

@property (nonatomic, strong)YWSearchResultController *searchResultController;

@property(nonatomic, strong)UIViewController* baseViewController;

@property (nonatomic, strong)UILabel *alertLabel;

@end

@implementation YWSearchCom

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(instancetype)initWithCurrentController:(UIViewController *)controller
{
    self = [super init];
    if (self)
    {
        self.baseViewController = controller;
        
        //初始化搜索结果控制器
        __weak typeof(self) weakSelf = self;
        self.searchResultController = [[YWSearchResultController alloc] init];
        self.searchResultController.baseViewController = controller;
        //搜索结果控制器操作回调
        self.searchResultController.cancelSearch = ^(BOOL cancelSearch)
        {
            [weakSelf cancelSearch:cancelSearch];
        };
        
        //初始化searchController
        self.searchViewController = [[UISearchController alloc]initWithSearchResultsController:self.searchResultController];
        //修改UISearchBar样式
        [self setupTableBar:_searchViewController.searchBar];
        self.searchViewController.active = NO;
        self.searchViewController.dimsBackgroundDuringPresentation = YES;
        self.searchViewController.hidesNavigationBarDuringPresentation = YES;
        self.searchViewController.searchResultsUpdater = self; //协议
        self.searchViewController.delegate = self;
        self.searchViewController.view.backgroundColor = RGB(247, 247, 249);
        
        //无结果提示
        self.alertLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, Main_Screen_Width, 100)];
        self.alertLabel.textAlignment = NSTextAlignmentCenter;
        //        self.alertLabel.font = [UIFont systemFontOfSize:14];
        self.alertLabel.textColor = RGB(34, 208, 180);
        self.alertLabel.text = @"暂无搜索结果";
        [self.searchViewController.view addSubview:self.alertLabel];
        
        [self initData];
        
        //监听通知----根控制器出现时（因为这里的push是借助根控制器来完成的）
    
        [[NSNotificationCenter defaultCenter] addObserverForName:@"Notification_ChangeSearchVCStyle" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note)
        {
            if (self.searchViewController.active)
            {
//                self.baseViewController.tabBarController.tabBar.hidden = YES;
                [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
            }
        }];
    }
    
    return self;
}

- (void)initData
{
    
}

//改变UISearchBar的样式，，，可以使用默认的------
-(void)setupTableBar:(UISearchBar *)bar
{
    bar.frame = CGRectMake(0, 0, 0, 44);
    bar.placeholder =  NSLocalizedString(@"搜索", @"A friendly greeting");
    [bar setSearchFieldBackgroundImage:[[UIImage imageNamed:@"search_input_1"]resizableImageWithCapInsets:UIEdgeInsetsMake(15.0, 18.0, 15.0, 18.0)] forState:UIControlStateNormal];
//    [bar setBackgroundImage:[[UIImage imageNamed:@"search_bg_1"] resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)]];
    
    [bar setImage:[UIImage imageNamed:@"消息-搜索图标"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];

    UITextField*searchField=[bar valueForKey:@"_searchField"];
    [searchField setValue:RGB(220, 220, 200) forKeyPath:@"_placeholderLabel.textColor"];
    bar.barTintColor = RGB(34, 208, 180);
    
    
    [bar setTintColor:RGB(34, 208, 180)];
    [bar setBarTintColor:RGB(247, 247, 249)];
    bar.barStyle = UIBarStyleBlack;
    [bar setBackgroundImage:[UIImage new]];
    bar.delegate =self;
    bar.backgroundColor = RGB(247, 247, 249);
    bar.autocorrectionType = UITextAutocorrectionTypeNo;//SearchBar输入内容时（英文),不要让它出现尾巴
    [bar setAutocapitalizationType:UITextAutocapitalizationTypeNone]; //设置键盘自动大小写的属性
    bar.tintColor = RGB(34, 208, 180);
    [bar sizeToFit];
    
}

#pragma mark -- UISearchControllerDelegate
- (void)didPresentSearchController:(UISearchController *)searchController
{
    //自己按照需求控制
//    self.baseViewController.tabBarController.tabBar.hidden = YES;
//    self.searchResultController.tableView.height = Main_Screen_Height;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)willDismissSearchController:(UISearchController *)searchController
{
    //自己按照需求控制
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
//    self.baseViewController.tabBarController.tabBar.hidden = NO;
}

#pragma mark -- UISearchBarDelegate
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
   
    return YES;
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
}

#pragma mark -- UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *searchString = searchController.searchBar.text;
  
    //自己按照需求控制
    if (searchString.length > 0) {
        self.alertLabel.hidden = YES;
    } else {
        self.alertLabel.hidden = NO;
    }
    [self filterContentForSearchText:searchString];
}

//源字符串内容是否包含或等于要搜索的字符串内容
-(void)filterContentForSearchText:(NSString*)searchText
{
    [self.searchResultController.tableView reloadData];
}


- (void)cancelSearch:(BOOL)cancelSearch
{
    __weak typeof(self) weakSelf = self;
    
    if (cancelSearch)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.searchViewController.active = NO;
        });
        
    } else {
        [weakSelf.searchViewController.searchBar resignFirstResponder];
    }
    
}

@end
